package com.system.boot.rbac.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.system.api.rbac.entity.po.SysRoleMenuRelation;
import com.system.api.rbac.entity.po.SysRolePermissionRelation;
import com.system.boot.rbac.mapper.RoleMenuRelationMapper;
import com.system.boot.rbac.mapper.RolePermissionRelationMapper;
import com.system.boot.rbac.service.RoleMenuService;
import com.system.boot.rbac.service.RolePermissionService;
import com.system.common.constant.SystemConstant;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.yang.common.core.exception.BaseException;
import org.yang.common.utils.jwt.JwtTokenAnalysisUtli;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 *  
 * @author: lslands
 * @description:   
 * @version：v1.0
 * @date:    2024/6/28 22:47
 */
@Service
public class RoleMenuServiceImpl extends ServiceImpl<RoleMenuRelationMapper, SysRoleMenuRelation> implements RoleMenuService {

    @Override
    public List<Long> getMenusByRole(Long roleId) throws BaseException {

        return baseMapper.selectMenusByRole(roleId);
    }

    @Transactional(rollbackFor = RuntimeException.class)
    @Override
    public boolean assignMenus(Long roleId, List<Long> menuIds) throws BaseException {
        List<SysRoleMenuRelation> relations = baseMapper
                .selectList(new LambdaQueryWrapper<SysRoleMenuRelation>().select(SysRoleMenuRelation::getMenuId)
                        .eq(SysRoleMenuRelation::getRoleId, roleId));
        if(relations.isEmpty()){
            List<SysRoleMenuRelation> list = menuIds.stream().map(x -> new SysRoleMenuRelation(roleId, x)).toList();
            return this.saveBatch(list);
        }
        List<Long> longList = relations.stream().map(SysRoleMenuRelation::getId).toList();
        //获取差集 -需要删除
        List<Long> deleteIds = CollectionUtils.subtract(longList, menuIds).stream().toList();
        if(!deleteIds.isEmpty()){
            baseMapper.deleteMenuIdsByBatch(deleteIds, JwtTokenAnalysisUtli.useId());
        }
        //获取补集 - 进行插入
        Set<Long> complementSet = new HashSet<>(menuIds);
        longList.forEach(complementSet::remove);
        if(!complementSet.isEmpty()){
            List<SysRoleMenuRelation> list = complementSet.stream()
                    .map(x -> new SysRoleMenuRelation(roleId, x)).toList();
            return this.saveBatch(list);
        }
        return true;
    }

}
